//
//  MsgController.m
//  BLE4.0Example
//
//  Created by zxy on 2017/9/28.
//  Copyright © 2017年 saint. All rights reserved.
//

#import "MsgController.h"
#import "YHBLECentralManager.h"
#import <AFNetworking/AFNetworkReachabilityManager.h>
#import <CocoaAsyncSocket/GCDAsyncSocket.h>
#import <CocoaAsyncSocket/GCDAsyncUdpSocket.h>


#import "AFNetworkReachabilityManager.h"
#import <SystemConfiguration/CaptiveNetwork.h>

#import <ifaddrs.h>
#import <arpa/inet.h>
#import <notify_keys.h>
#import <NSData+FastHex.h>
#import <sys/sysctl.h>
#import <net/if.h>
#import <net/if_dl.h>
@interface MsgController ()
@property (weak, nonatomic) IBOutlet UIActivityIndicatorView *hud;
@property (weak, nonatomic) IBOutlet UITextField *wifiName;
@property (weak, nonatomic) IBOutlet UITextField *wifiPasswd;
@property (weak, nonatomic) IBOutlet UITextView *msgContent;
@property (weak, nonatomic) IBOutlet UISegmentedControl *wfiiType;
@property (weak, nonatomic) IBOutlet UITextView *sendContent;


@end

@implementation MsgController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    
    AFNetworkReachabilityManager *afNetworkReachabilityManager =
    [AFNetworkReachabilityManager sharedManager];
    //开启网络监视器；
    [afNetworkReachabilityManager startMonitoring];
    
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(monitoringNetWithNotification:) name:AFNetworkingReachabilityDidChangeNotification object:nil];
    
    [self fetchWifiInfo];
  
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(msgCaming) name:YH_BLE_MESSAGE_COMMING object:nil];
}

- (instancetype)fetchWifiInfo {
    NSDictionary  *dicInfo = [self fetchSSIDInfo];
    self.wifiName.text = dicInfo[@"SSID"];
    NSString *str = [[NSString alloc]initWithData:dicInfo[@"SSIDDATA"] encoding:NSUTF8StringEncoding];
    return self;
}

- (id)fetchSSIDInfo {
    
    NSArray *ifs = (__bridge_transfer id)CNCopySupportedInterfaces();
    id info = nil;
    for (NSString *ifnam in ifs) {
        info = (__bridge_transfer id)CNCopyCurrentNetworkInfo((__bridge CFStringRef)ifnam);
        if (info && [info count]) { break; }
    }
    return info;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

unsigned short fmsn = 0x0000;
- (IBAction)sendMsg:(id)sender {
    
    
    NSData *nameData = [self.wifiName.text dataUsingEncoding:NSUTF8StringEncoding];
    nameData = [self fix32with:nameData];
    NSData *passWd = [self.wifiName.text dataUsingEncoding:NSUTF8StringEncoding];
    passWd = [self fix32with:passWd];
    Byte type[] = {0x00,0x01,0x02};
    NSData *typeData = [NSData dataWithBytes:&type[self.wfiiType.selectedSegmentIndex] length:1];
    
    NSMutableData *conntentData = [[NSMutableData alloc]init];
    [conntentData appendData:[NSData dataWithBytes:(Byte[]){0xc0,0x06} length:2]];
    
    char nameLenght = (char)self.wifiName.text.length;
    [conntentData appendData:[NSData dataWithBytes:&nameLenght length:1]];
    [conntentData appendData:nameData];
    char passwdLenght = (char)self.wifiPasswd.text.length;
    [conntentData appendData:[NSData dataWithBytes:&passwdLenght length:1]];
    [conntentData appendData:passWd];
    [conntentData appendData:typeData];

    short lenght = conntentData.length;
    lenght = CFSwapInt16(lenght);
    NSData *lenghtData =  [NSData dataWithBytes:&lenght length:sizeof(short)];
    NSMutableData *data = [NSMutableData dataWithHexString:@"a55a0000c0"];
    [data appendData:lenghtData];
    [data appendData:conntentData];
    
    
    
    //数据字节内容的和，用于校验位
    int sum = 0;
    
    for (NSInteger loc = 0; loc<data.length; ++loc){
        Byte dataByte;
        [data getBytes:&dataByte range:NSMakeRange(loc, 1)];
        sum += dataByte;
    }
    
    //校验位，前面字节和取反
    Byte checkSum = -sum;
    
    
    [data appendBytes:&checkSum length:sizeof(checkSum)];
    
    [[YHBLECentralManager shared] sendMessage:data];
    
    NSLog(@"发送的数据---- %@",data);
    self.sendContent.text = [NSString stringWithFormat:@"%@",data];
    
    
    
    
   }
- (IBAction)clear:(id)sender {
    [YHBLECentralManager shared].reciveBuffer = nil;
    self.msgContent.text = @"";;
}
- (IBAction)clearsend:(id)sender {
    self.sendContent.text = @"";
}



- (void)msgCaming{
    dispatch_async(dispatch_get_main_queue(), ^{
        self.msgContent.text = [NSString stringWithFormat:@"%@",[YHBLECentralManager shared].reciveBuffer];
    });
    
}


- (NSData *)fix32with:(NSData *)data{
    if (data.length != 32) {
        int fixLenght = (int)(32 - data.length);
        NSMutableData *fixData = [[NSMutableData alloc]initWithLength:fixLenght];
        NSMutableData *realData = [NSMutableData dataWithData:data];
        [realData appendData:fixData];
//        [fixData appendData:data];
        return realData;
    }
    return data;
}


- (void)dealloc{
    [[YHBLECentralManager shared].centerManager cancelPeripheralConnection:[YHBLECentralManager shared].currentConnectedPeripheral];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
